package cn.flying.cloud.flow.context;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import cn.flying.cloud.base.common.exception.CommonException;
import cn.flying.cloud.flow.annotation.FormKey;

/**
 * @author: admin
 * @date: 2024年12月17日 21:50
 * @version: 1.0
 */
public abstract class FlowAuditForwardAbstract implements InitializingBean {

    protected Map<String, Method> methodMap = new ConcurrentHashMap<>();

    /**
     *
     */
    @Override
    public void afterPropertiesSet() {
        Class<? extends FlowAuditForwardAbstract> clazz = this.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        if (methods == null || methods.length == 0) {
            return;
        }
        Arrays.stream(methods).filter(method -> method.isAnnotationPresent(FormKey.class)).forEach(method -> {
            FormKey formKey = method.getAnnotation(FormKey.class);
            if (StringUtils.isEmpty(formKey.name())) {
                throw new CommonException("指定的Method的FormKey为空");
            }
            methodMap.put(formKey.name(), method);
        });
    }

    /**
     * 跳转到指定页面
     *
     * @param procInstId
     * @param formKey
     * @param model
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public String turnAudit(String procInstId, String formKey, Model model) throws InvocationTargetException, IllegalAccessException {
        Method method = methodMap.get(formKey);
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes == null || parameterTypes.length == 0) {
            return (String) method.invoke(this, model);
        } else {
            return (String) method.invoke(this, procInstId, model);
        }
    }


}
